<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Utils\MysqlBackup;
use App\Models\User;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Http\Request;
use App\Jobs\BackupDatabase;
use Illuminate\Support\Facades\Auth;

class BackupController extends Controller
{

  /**
   * @var \App\Repositories\Contracts\AttachmentRepositoryInterface
   */
  private $attachmentRepository;


  public function lists(Request $request)
  {

    $mysqlBackup = new MysqlBackup();
    $backupInfo = $mysqlBackup->getBackupInfo();
    $prePage = 10;
    $totalNum = count($backupInfo);
    if ($totalNum < 1) {
      $paginatedSearchResults = new LengthAwarePaginator(null, 0, $prePage);
      return $this->result(true,$paginatedSearchResults);
    }
    $pageData = array_chunk($backupInfo, $prePage);
    unset($backupInfo);
    $currentPage = LengthAwarePaginator::resolveCurrentPage();
    $backupInfo = $pageData[$currentPage - 1];
    $userIds = array_unique(array_column($backupInfo, 'user_id'));
    $users = User::find($userIds);
    $names = null;
    if ($users) {
      $users = $users->toArray();
      $names = array_column($users, 'name', 'id');
    }
    array_walk($backupInfo, function(&$value )use($names){
      if( $names != null && array_key_exists($value['user_id'],$names)){
          $value['user_name'] = $names[$value['user_id']];
      }else {
          $value['user_name'] = 'none';
      }
   });
   $paginatedSearchResults= new LengthAwarePaginator($backupInfo, $totalNum,$prePage,$currentPage,['path'=>$request->url()]);
   return $this->resultData($paginatedSearchResults);
  }

  public function backup()
  {
    $userId=Auth::id();
    $this->dispatch(new BackupDatabase($userId));
    return $this->result(true);
  }

  public function remove($name)
  {
    $mysqlBackup = new MysqlBackup();
    $mysqlBackup->removeBackup($name);
    return $this->result(true);
  }
}
